package com.nondo.rdp.finance.service.impl.product;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.product.FinanceProductBuy;
import com.nondo.rdp.finance.repository.product.FinanceProductBuyRepository;
import com.nondo.rdp.finance.service.product.FinanceProductBuyService;

@Transactional
@Service
public class FinanceProductBuyServiceImpl implements FinanceProductBuyService {
    @Autowired
    FinanceProductBuyRepository financeProductBuyRepository;

    @Override
    public FinanceProductBuy findOne(Long id) {
        return this.financeProductBuyRepository.findOne(id);
    }

    @Override
    public FinanceProductBuy save(FinanceProductBuy financeProductBuy) {
        return this.financeProductBuyRepository.save(financeProductBuy);
    }

    @Override
    public void update(FinanceProductBuy financeProductBuy) {
        this.financeProductBuyRepository.delete(financeProductBuy.getId());
    }

    @Override
    public void delete(Long id) {
        this.financeProductBuyRepository.deleteById(id);
    }

    @Override
    public Page<FinanceProductBuy> findAll(Page<FinanceProductBuy> page, FinanceProductBuy financeProductBuy) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<FinanceProductBuy> dictPage = financeProductBuyRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotEmpty(financeProductBuy.getProduct().getTitle())) {
                predicates.add(builder.like(root.get("title"), "%" + financeProductBuy.getProduct().getTitle() + "%"));
            }
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_DELETE));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<FinanceProductBuy>(dictPage);
    }
}